<template>
  <div class="emp-table-page">
    <el-card>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center">
          <span>我的岗位管理</span>
          <div style="display: flex; align-items: center; gap: 8px">
            <el-button @click="refreshCurrentMode" :loading="loading">刷新</el-button>
            <el-button v-if="!postMode" @click="openConditionDialog">条件查询</el-button>
            <el-button v-if="postMode" @click="switchToGet">重置为全部</el-button>
            <el-button type="primary" @click="openAddDialog">添加岗位</el-button>
          </div>
        </div>
      </template>
      <el-table :data="userList" v-loading="loading" style="width: 100%; margin-bottom: 16px">
        <el-table-column prop="id" label="职位id" width="60" />
        <el-table-column prop="title" label="职位名称" width="120" />
        <el-table-column prop="salary" label="薪水" width="100" />
        <el-table-column prop="companyName" label="公司名称" width="140" />
        <el-table-column prop="companySize" label="公司规模" width="70" />
        <el-table-column prop="location" label="公司所在地" width="80" />
        <el-table-column prop="experience" label="经验要求" width="80" />
        <el-table-column prop="education" label="学历要求" width="100" />
        <el-table-column prop="type" label="职位类型" width="60" />
        <el-table-column prop="benefits" label="职位待遇福利" width="180" />
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :loading="deleteLoadingId === scope.row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div
      style="display: flex; justify-content: space-between; align-items: center; margin-top: 8px"
    >
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNum"
        @current-change="handlePageChange"
      />
      <div style="display: flex; align-items: center; gap: 8px">
        <span>每页条数：</span>
        <el-input-number
          v-model="inputPageSize"
          :min="1"
          :max="100"
          size="small"
          style="width: 100px"
          :step="1"
          placeholder="每页条数"
        />
        <el-button @click="applyPageInput">跳转分页</el-button>
      </div>
    </div>

    <!-- 条件查询弹窗 -->
    <el-dialog title="条件查询" v-model="conditionDialogVisible" width="500px">
      <el-form :model="conditionForm" label-width="90px">
        <el-form-item label="职位名称">
          <el-input v-model="conditionForm.title" clearable />
        </el-form-item>
        <el-form-item label="薪水">
          <el-input v-model="conditionForm.salary" clearable />
        </el-form-item>
        <el-form-item label="公司规模">
          <el-select v-model="conditionForm.companySize" clearable placeholder="请选择">
            <el-option label="大型" value="大型" />
            <el-option label="中型" value="中型" />
            <el-option label="小型" value="小型" />
          </el-select>
        </el-form-item>
        <el-form-item label="公司所在地">
          <el-input v-model="conditionForm.location" clearable />
        </el-form-item>
        <el-form-item label="经验要求">
          <el-select v-model="conditionForm.experience" clearable placeholder="请选择">
            <el-option label="1年以上" value="1年以上" />
            <el-option label="2年以上" value="2年以上" />
            <el-option label="3年以上" value="3年以上" />
            <el-option label="4年以上" value="4年以上" />
            <el-option label="5年以上" value="5年以上" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历要求">
          <el-select v-model="conditionForm.education" clearable placeholder="请选择">
            <el-option label="大专及以上" value="大专及以上" />
            <el-option label="本科及以上" value="本科及以上" />
            <el-option label="硕士及以上" value="硕士及以上" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位类型">
          <el-select v-model="conditionForm.type" clearable placeholder="请选择">
            <el-option label="兼职" value="兼职" />
            <el-option label="全职" value="全职" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位待遇福利">
          <el-input v-model="conditionForm.benefits" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="conditionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="applyCondition">查询</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑岗位弹窗 -->
    <el-dialog
      :title="dialogMode === 'add' ? '添加岗位' : '编辑岗位'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="职位名称" prop="title">
          <el-input v-model="form.title" clearable />
        </el-form-item>
        <el-form-item label="薪水" prop="salary">
          <el-input v-model="form.salary" clearable />
        </el-form-item>
        <el-form-item label="公司规模" prop="companySize">
          <el-select v-model="form.companySize" clearable placeholder="请选择">
            <el-option label="大型" value="大型" />
            <el-option label="中型" value="中型" />
            <el-option label="小型" value="小型" />
          </el-select>
        </el-form-item>
        <el-form-item label="公司所在地" prop="location">
          <el-input v-model="form.location" clearable />
        </el-form-item>
        <el-form-item label="经验要求" prop="experience">
          <el-select v-model="form.experience" clearable placeholder="请选择">
            <el-option label="1年以上" value="1年以上" />
            <el-option label="2年以上" value="2年以上" />
            <el-option label="3年以上" value="3年以上" />
            <el-option label="4年以上" value="4年以上" />
            <el-option label="5年以上" value="5年以上" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历要求" prop="education">
          <el-select v-model="form.education" clearable placeholder="请选择">
            <el-option label="大专及以上" value="大专及以上" />
            <el-option label="本科及以上" value="本科及以上" />
            <el-option label="硕士及以上" value="硕士及以上" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位类型" prop="type">
          <el-select v-model="form.type" clearable placeholder="请选择">
            <el-option label="兼职" value="兼职" />
            <el-option label="全职" value="全职" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位待遇福利" prop="benefits">
          <el-input v-model="form.benefits" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="dialogLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getEmpList, addEmp, updateEmp, deleteEmp, getAllEmps } from '@/api/emp'
import { showCustomMessage } from '@/utils/message'
import type { FormInstance, FormRules } from 'element-plus'

const userList = ref<any[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const inputPageNum = ref(1)
const inputPageSize = ref(10)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const dialogLoading = ref(false)
const deleteLoadingId = ref<number | null>(null)
const formRef = ref<FormInstance>()
const postMode = ref(false)
const conditionDialogVisible = ref(false)
const currentCompany = localStorage.getItem('companyUsername') || ''

const conditionForm: Record<string, any> = reactive({
  title: '',
  salary: '',
  companySize: '',
  location: '',
  experience: '',
  education: '',
  type: '',
  benefits: '',
})
let lastCondition: Record<string, any> = {}

const form = reactive({
  id: undefined,
  title: '',
  salary: '',
  companyName: currentCompany,
  companySize: '',
  location: '',
  experience: '',
  education: '',
  type: '',
  benefits: '',
})

const rules: FormRules = {
  title: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
  salary: [{ required: true, message: '请输入薪水', trigger: 'blur' }],
  companySize: [{ required: true, message: '请选择公司规模', trigger: 'blur' }],
  location: [{ required: true, message: '请输入公司所在地', trigger: 'blur' }],
  experience: [{ required: true, message: '请选择经验要求', trigger: 'blur' }],
  education: [{ required: true, message: '请选择学历要求', trigger: 'blur' }],
  type: [{ required: true, message: '请选择职位类型', trigger: 'blur' }],
  benefits: [{ required: true, message: '请输入职位待遇福利', trigger: 'blur' }],
}

// 只查当前公司岗位
const fetchEmpsGet = async () => {
  loading.value = true
  try {
    const response = await getAllEmps({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      companyName: currentCompany,
    })
    userList.value = response.data.list || []
    total.value = response.data.total || response.data.length || 0
    postMode.value = false
    showCustomMessage('获取岗位成功', 'success')
  } catch (error: any) {
    showCustomMessage('获取岗位失败: ' + error.message, 'error')
  } finally {
    loading.value = false
  }
}

// 条件查询也只查本公司
const fetchEmpsPost = async (condition: Record<string, any> = {}) => {
  loading.value = true
  try {
    const params: Record<string, any> = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      companyName: currentCompany,
      ...condition,
    }
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === undefined || params[key] === null) {
        delete params[key]
      }
    })
    const response = await getEmpList(params)
    userList.value = response.data.list || []
    total.value = response.data.total || response.data.length || 0
    postMode.value = true
    showCustomMessage('条件查询成功', 'success')
  } catch (error: any) {
    showCustomMessage('条件查询失败: ' + error.message, 'error')
  } finally {
    loading.value = false
  }
}

const openConditionDialog = () => {
  conditionDialogVisible.value = true
}

const applyCondition = () => {
  pageNum.value = 1
  inputPageNum.value = 1
  lastCondition = { ...conditionForm }
  conditionDialogVisible.value = false
  fetchEmpsPost(lastCondition)
}

const switchToGet = () => {
  pageNum.value = 1
  inputPageNum.value = 1
  Object.keys(conditionForm).forEach((key) => (conditionForm[key] = ''))
  lastCondition = {}
  fetchEmpsGet()
}

const refreshCurrentMode = () => {
  if (postMode.value) {
    fetchEmpsPost(lastCondition)
  } else {
    fetchEmpsGet()
  }
}

const handlePageChange = (val: number) => {
  pageNum.value = val
  inputPageNum.value = val
  refreshCurrentMode()
}

const applyPageInput = () => {
  if (inputPageNum.value < 1) inputPageNum.value = 1
  if (inputPageSize.value < 1) inputPageSize.value = 1
  pageNum.value = inputPageNum.value
  pageSize.value = inputPageSize.value
  refreshCurrentMode()
}

const openAddDialog = () => {
  dialogMode.value = 'add'
  Object.assign(form, {
    id: undefined,
    title: '',
    salary: '',
    companyName: currentCompany,
    companySize: '',
    location: '',
    experience: '',
    education: '',
    type: '',
    benefits: '',
  })
  dialogVisible.value = true
}

const openEditDialog = (row: any) => {
  dialogMode.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    dialogLoading.value = true
    try {
      if (dialogMode.value === 'add') {
        form.companyName = currentCompany // 保证添加时公司名为当前公司
        await addEmp(form)
        showCustomMessage('添加岗位成功', 'success')
      } else {
        await updateEmp(form)
        showCustomMessage('编辑岗位成功', 'success')
      }
      dialogVisible.value = false
      refreshCurrentMode()
    } catch (error: any) {
      showCustomMessage(
        (dialogMode.value === 'add' ? '添加' : '编辑') + '岗位失败: ' + error.message,
        'error',
      )
    } finally {
      dialogLoading.value = false
    }
  })
}

const handleDelete = async (row: any) => {
  if (!row.id) return
  if (!confirm(`确定要删除职位 ${row.title} 吗？`)) return
  deleteLoadingId.value = row.id
  try {
    await deleteEmp(row.id)
    showCustomMessage('删除岗位成功', 'success')
    refreshCurrentMode()
  } catch (error: any) {
    showCustomMessage('删除岗位失败: ' + error.message, 'error')
  } finally {
    deleteLoadingId.value = null
  }
}

onMounted(() => {
  fetchEmpsGet()
})
</script>

<style scoped>
.emp-table-page {
  padding: 20px;
}
</style>
